﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Concurrency;

namespace RxPowerToys.ObservableExtensions
{
    public static class DynamicReturn
    {
        /// <summary>
        /// Generates a dynamic value by evaluating a function each time a subscriber subscribes.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="valueGenerator">Function delegate called for each new subscription.</param>
        /// <returns></returns>
        public static IObservable<T> Evaluate<T>(Func<T> valueGenerator)
        {
            return Scheduler.Immediate.Evaluate(valueGenerator);
        }

        public static IObservable<T> Evaluate<T>(this IScheduler scheduler, Func<T> valueGenerator)
        {
            return Observable.CreateWithDisposable<T>(
                o => scheduler.Schedule(() =>
                {
                    try
                    {
                        o.OnNext(valueGenerator());
                        o.OnCompleted();
                    }
                    catch (Exception e)
                    {
                        o.OnError(e);
                    }
                })
            );
        }
    }
}
